﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.ServiceProcess;
using System.Configuration;
using Entidades;
using System.Collections;
using Entidades.Model;
using Entidades.Helper;
using Microsoft.Win32;

namespace Configurator
{
    public partial class frm_Main : Form
    {
        List<reglasN> listaReglas = new List<reglasN>();

        public frm_Main()
        {
            

            InitializeComponent();
        }

        private void btn_SaveAppConf_Click(object sender, EventArgs e)
        {
            try
            {
                string exePath = System.IO.Path.Combine(
                Environment.CurrentDirectory, "DuplicateCheckService.exe");
                System.Configuration.Configuration config= ConfigurationManager.OpenExeConfiguration(exePath);
                Console.WriteLine(exePath);
                AppSettingsSection appS = config.AppSettings;

                appS.Settings.Remove("LogLocation");
                appS.Settings.Add("LogLocation", txt_Logs.Text.Trim());

                appS.Settings.Remove("LogMaxSizeBytes");
                appS.Settings.Add("LogMaxSizeBytes", txt_LogSize.Text.Trim());

                appS.Settings.Remove("IIFUser");
                appS.Settings.Add("IIFUser", txtUserIIF.Text.Trim());

                appS.Settings.Remove("IIFPassword");
                appS.Settings.Add("IIFPassword", txtPassIIF.Text.Trim());

                appS.Settings.Remove("IIFDomain");
                appS.Settings.Add("IIFDomain", txtDomainIIF.Text.Trim());

                appS.Settings.Remove("InputQueue");
                appS.Settings.Add("InputQueue", txt_EntryQueue.Text.Trim());

                appS.Settings.Remove("SchedulesTimes");
                appS.Settings.Add("SchedulesTimes", txt_timeExec.Text.Trim());

                appS.Settings.Remove("DelayMinutes");
                appS.Settings.Add("DelayMinutes", txtWaitMinutes.Text.Trim());

                appS.Settings.Remove("StringConnection");
                appS.Settings.Add("StringConnection", txtCadenaBD.Text.Trim());

                appS.Settings.Remove("SystemID");
                appS.Settings.Add("SystemID", txt_Sistema.Text.Trim());

                appS.Settings.Remove("ReadCommand");
                appS.Settings.Add("ReadCommand", txt_comLectura.Text.Trim());

                appS.Settings.Remove("UpdateCommand");
                appS.Settings.Add("UpdateCommand", txt_comActualizacion.Text.Trim());

                appS.Settings.Remove("SearchQueues");
                appS.Settings.Add("SearchQueues", txt_Sistema.Text.Trim());

                appS.Settings.Remove("EmailAccountTo");
                appS.Settings.Add("EmailAccountTo", txtEmailTo.Text.Trim());

                appS.Settings.Remove("DuplicateRules");
                appS.Settings.Add("DuplicateRules", txtReglasNegocio.Text.Trim());
                

                config.Save(ConfigurationSaveMode.Modified);

                MessageBox.Show("La configuración ha sido guardada exitosamente.", "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Unisys Duplicate Check Service Configurator",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void btn_CancelAppConf_Click(object sender, EventArgs e)
        {
            loadAppConfig();
        }

        private void btn_ServiceP_Click(object sender, EventArgs e)
        {
            if (btn_ServiceP.BackColor.Equals(Color.Green))
            {
                stopService();
            }
            else { startService(); }
        }

        private void stopService()
        {
            ServiceController sc = new ServiceController("DuplicateCheckService");
            try
            {
                if (sc.Status == ServiceControllerStatus.Running)
                {
                    sc.Stop();
                    btn_ServiceP.BackColor = Color.Red;
                }
                sc.WaitForStatus(ServiceControllerStatus.Stopped);
                sc.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void startService()
        {
            ServiceController sc = new ServiceController("DuplicateCheckService");
            try
            {
                if (sc != null && sc.Status == ServiceControllerStatus.Stopped)
                {

                    sc.Start();
                    btn_ServiceP.BackColor = Color.Green;
                }
                sc.WaitForStatus(ServiceControllerStatus.Running);
                sc.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void loadBusinessRules()
        {
            Entidades.Model.DuplicateService bussinessRulesLoaded = Deserializer.Deserialize<DuplicateService>("C://prueba.xml");
            listaReglas = new List<reglasN>();

            foreach (Incosistence incVal in bussinessRulesLoaded.IncosistenciesList)
            {
                reglasN newRule = new reglasN();
                newRule.tipo = 0;
                newRule.documentActions = incVal.DocActions;
                newRule.ExitQueue = incVal.outputQueue;
                newRule.forceWIP = incVal.ForceOutputWip;
                newRule.indFields = incVal.Fields;
                newRule.name = incVal.Name;
                newRule.newName = incVal.NewName;

                listaReglas.Add(newRule);
                listBox1.Items.Add("Regla Negocio ");
            }

            foreach (DocClassExc incVal in bussinessRulesLoaded.DocClassExcList)
            {
                reglasN newRule = new reglasN();
                newRule.tipo = 1;
                newRule.documentActions = incVal.DocActions;
                newRule.ExitQueue = incVal.outputQueue;
                newRule.forceWIP = incVal.ForceOutputWip;
                newRule.indFields = incVal.Fields;
                newRule.name = incVal.Name;
                newRule.newName = incVal.NewName;

                listaReglas.Add(newRule);
                listBox1.Items.Add("Regla Negocio ");
            }

            foreach (DocClass incVal in bussinessRulesLoaded.DocClassList)
            {
                reglasN newRule = new reglasN();
                newRule.tipo = 2;
                newRule.documentActions = incVal.DocActions;
                newRule.ExitQueue = incVal.outputQueue;
                newRule.forceWIP = incVal.ForceOutputWip;
                newRule.indFields = incVal.Fields;
                newRule.name = incVal.Name;
                newRule.newName = incVal.NewName;
                newRule.date = incVal.DateFieldName;
                newRule.formatDate = incVal.DateFieldFormat;

                listaReglas.Add(newRule);
                listBox1.Items.Add("Regla Negocio ");
            }



            if (listBox1.Items.Count > 0)
            {
                panel1.Enabled = true;
                button3.Enabled = true;
                
                listBox1.Select();
                listBox1.SelectedIndex = 0;

                
            }

            




        }

        private void loadAppConfig()
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(Environment.CurrentDirectory + "/DuplicateCheckService.exe.config");
                XmlNodeList configuraciones = xDoc.GetElementsByTagName("appSettings");
                XmlNodeList lista = ((XmlElement)configuraciones[0]).GetElementsByTagName("add");

                foreach (XmlElement nodo in lista)
                {
                    switch (nodo.GetAttribute("key"))
                    {
                        case "LogLocation":
                            txt_Logs.Text = nodo.GetAttribute("value");

                            break;
                        case "LogMaxSizeBytes":
                            txt_LogSize.Text = nodo.GetAttribute("value");
                            break;

                        case "IIFUser":
                            txtUserIIF.Text = nodo.GetAttribute("value");
                            break;

                        case "IIFPassword":
                            txtPassIIF.Text = nodo.GetAttribute("value");
                            break;

                        case "IIFDomain":
                            txtDomainIIF.Text = nodo.GetAttribute("value");
                            break;

                        case "InputQueue":
                            txt_EntryQueue.Text = nodo.GetAttribute("value");
                            break;

                        case "SchedulesTimes":
                            txt_timeExec.Text = nodo.GetAttribute("value");
                            break;

                        case "DelayMinutes":
                            txtWaitMinutes.Text = nodo.GetAttribute("value");
                            break;

                        case "StringConnection":
                            txtCadenaBD.Text = nodo.GetAttribute("value");
                            break;

                        case "SystemID":
                            txt_Sistema.Text = nodo.GetAttribute("value");
                            break;

                        case "ReadCommand":
                            txt_comLectura.Text = nodo.GetAttribute("value");
                            break;

                        case "UpdateCommand":
                            txt_comActualizacion.Text = nodo.GetAttribute("value");
                            break;

                        case "SearchQueues":
                            txtColasBusqueda.Text = nodo.GetAttribute("value");
                            break;

                        case "EmailAccountTo":
                            txtEmailTo.Text = nodo.GetAttribute("value");
                            break;

                        case "DuplicateRules":
                            txtReglasNegocio.Text = nodo.GetAttribute("value");
                            break;

                    }


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void frm_Main_Load(object sender, EventArgs e)
        {
            
            //try
            //{
            //    //loadAppConfig();
                    loadBusinessRules();
                    loadRegistryEntries();
            //    ServiceController sc = new ServiceController("DuplicateCheckService");
            //    if (sc == null)
            //    {
            //        MessageBox.Show("El Servicio no se encuentra instalado.", "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //        Environment.Exit(0);
            //    }
            //    else if (sc.Status == ServiceControllerStatus.Running)
            //    {
            //        btn_ServiceP.BackColor = Color.Green;
            //    }
            //    else
            //    {
            //        btn_ServiceP.BackColor = Color.Red;
            //    }
                

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    Environment.Exit(0);
            //}
            
        }

        private void btn_FindLogs_Click(object sender, EventArgs e)
        {
            //fbd_Find.SelectedPath = "C:\\";
            DialogResult result = fbd_Find.ShowDialog();
            if (result.ToString() == "OK")
            {
                txt_Logs.Text = fbd_Find.SelectedPath;
            }
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void btn_FindBussinessRules_Click(object sender, EventArgs e)
        {
            //fbd_Find.SelectedPath = "C:\\";
            DialogResult result = fbd_Find.ShowDialog();
            if (result.ToString() == "OK")
            {
                txtReglasNegocio.Text = fbd_Find.SelectedPath;
            }
        }

        private void btn_SaveBusRules_Click(object sender, EventArgs e)
        {
            
                Entidades.Model.DuplicateService bussinessRulesSave = new Entidades.Model.DuplicateService();
                bussinessRulesSave.DocClassExcList = new List<Entidades.Model.DocClassExc>();
                bussinessRulesSave.IncosistenciesList = new List<Entidades.Model.Incosistence>();
                bussinessRulesSave.DocClassList = new List<Entidades.Model.DocClass>();

                for (int ind = 0; ind < listaReglas.Count; ind++)
                {
                    if (listaReglas[ind].tipo == 0)
                    {
                        Incosistence newInconsistence = new Incosistence();
                        newInconsistence.DocActions = listaReglas[ind].documentActions;
                        newInconsistence.Fields = listaReglas[ind].indFields;
                        newInconsistence.ForceOutputWip = bool.Parse(listaReglas[ind].forceWIP.ToString());
                        newInconsistence.Name = listaReglas[ind].name;
                        newInconsistence.NewName = listaReglas[ind].newName;
                        newInconsistence.outputQueue = listaReglas[ind].ExitQueue;
                        bussinessRulesSave.IncosistenciesList.Add(newInconsistence);
                        
                    }
                    else if (listaReglas[ind].tipo == 1)
                    {
                        DocClassExc newException = new DocClassExc();
                        newException.DocActions = listaReglas[ind].documentActions;
                        newException.Fields = listaReglas[ind].indFields;
                        newException.ForceOutputWip = bool.Parse(listaReglas[ind].forceWIP.ToString());
                        newException.Name = listaReglas[ind].name;
                        newException.NewName = listaReglas[ind].newName;
                        newException.outputQueue = listaReglas[ind].ExitQueue;
                        bussinessRulesSave.DocClassExcList.Add(newException);
                    }
                    else if (listaReglas[ind].tipo == 2)
                    {
                        DocClass newDocClass = new DocClass();
                        newDocClass.DocActions = listaReglas[ind].documentActions;
                        newDocClass.Fields = listaReglas[ind].indFields;
                        newDocClass.ForceOutputWip = bool.Parse(listaReglas[ind].forceWIP.ToString());
                        newDocClass.Name = listaReglas[ind].name;
                        newDocClass.NewName = listaReglas[ind].newName;
                        newDocClass.outputQueue = listaReglas[ind].ExitQueue;
                        newDocClass.DateFieldFormat = listaReglas[ind].formatDate;
                        newDocClass.DateFieldName = listaReglas[ind].date;
                        bussinessRulesSave.DocClassList.Add(newDocClass);
                    }
                }


                    //Send to XML File
                    Serializer.XmlSerializeToFile(bussinessRulesSave, "C://prueba.xml");//Entidades.Configuration.duplicateRules);

                    MessageBox.Show("Archivo de Reglas de Negocio generado correctamente", "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Information);

            
        }

        private void BusinessRulesTable_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }


            
   

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                List<IndexField> selectedItemList = listaReglas[listBox1.SelectedIndex].indFields;
                IndexFieldsTable.Rows.Clear();
                foreach (IndexField indField in selectedItemList)
                {
                    IndexFieldsTable.Rows.Add(indField.Name, indField.Value);
                }
                comboBox1.SelectedIndex = listaReglas[listBox1.SelectedIndex].tipo;
                if (listaReglas[listBox1.SelectedIndex].forceWIP)
                    comboBox2.SelectedIndex = 1;
                else
                    comboBox2.SelectedIndex = 0;

                textBox1.Text = listaReglas[listBox1.SelectedIndex].name;
                textBox2.Text = listaReglas[listBox1.SelectedIndex].newName;
                textBox3.Text = listaReglas[listBox1.SelectedIndex].date;
                textBox4.Text = listaReglas[listBox1.SelectedIndex].formatDate;
                textBox5.Text = listaReglas[listBox1.SelectedIndex].ExitQueue;
                textBox6.Text = listaReglas[listBox1.SelectedIndex].documentActions;

            }
            catch (Exception w) { /*MessageBox.Show(w.Message);*/ }
        }

        private void IndexFieldsTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                listaReglas[listBox1.SelectedIndex].indFields.Clear();
                for (int i = 0; i < IndexFieldsTable.Rows.Count-1;i++ )
                {
                    IndexField nuevoIndex = new IndexField();
                    nuevoIndex.Name = IndexFieldsTable.Rows[i].Cells[0].Value.ToString().Trim();
                    nuevoIndex.Value = IndexFieldsTable.Rows[i].Cells[1].Value.ToString().Trim();
                    listaReglas[listBox1.SelectedIndex].indFields.Add(nuevoIndex);

                }
            }
            catch (Exception w) { /*MessageBox.Show(w.Message);*/ }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int val = listBox1.Items.Count + 1;
            listBox1.Items.Add("Regla Negocio ");
            
            
            
            
            
            
            panel1.Enabled = true;
            button3.Enabled = true;

            listBox1.Select();
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            listaReglas.Add(new reglasN());
            listaReglas[listBox1.SelectedIndex].indFields.Add(new IndexField());
            
            

        
        }

        
        private class reglasN
        {
            public int tipo;//0=inc,1=excep,2=claseDoc
            public String documentActions ;
            public bool forceWIP;
            public String name;
            public String newName ;
            public String ExitQueue ;
            public String date ;
            public String formatDate ;
            public List<IndexField> indFields = new List<IndexField>();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                listaReglas[listBox1.SelectedIndex].tipo = comboBox1.SelectedIndex;

                if (comboBox1.SelectedIndex == 0)
                {
                    textBox3.Enabled = false;
                    textBox4.Enabled = false;
                    textBox3.Text = "";
                    textBox4.Text = "";
                }
                else if (comboBox1.SelectedIndex == 1)
                {
                    textBox3.Enabled = false;
                    textBox4.Enabled = false;
                    textBox3.Text = "";
                    textBox4.Text = "";
                }
                else if (comboBox1.SelectedIndex == 2)
                {
                    textBox3.Enabled = true;
                    textBox4.Enabled = true;
                }
            }
            catch { }

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            listaReglas[listBox1.SelectedIndex].name = textBox1.Text.Trim();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            listaReglas[listBox1.SelectedIndex].newName = textBox2.Text.Trim();
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            listaReglas[listBox1.SelectedIndex].date = textBox3.Text.Trim();
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            listaReglas[listBox1.SelectedIndex].formatDate = textBox4.Text.Trim();
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            listaReglas[listBox1.SelectedIndex].ExitQueue = textBox5.Text.Trim();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex == 0)
                listaReglas[listBox1.SelectedIndex].forceWIP = false;
            else
                listaReglas[listBox1.SelectedIndex].forceWIP = true;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            listaReglas[listBox1.SelectedIndex].documentActions = textBox6.Text.Trim();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex >= 0)
            {
                listaReglas.RemoveAt(listBox1.SelectedIndex);
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }
            listBox1.SelectedIndex = -1;

            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";

            if (listBox1.Items.Count == 0)
            {
                panel1.Enabled = false;
                button3.Enabled = false;
            }
            else
            {
                panel1.Enabled = true;
                button3.Enabled = true;
            }

        }

        private void btn_GuardarRegis_Click(object sender, EventArgs e)
        {
            String registry = "HKEY_LOCAL_MACHINE\\Software\\Unisys\\Unisys Duplicate Check Service";
            Registry.SetValue(registry, "Configuration_Error", chx_ConfigurationError.Checked.ToString());

            Registry.SetValue(registry, "FileSystemLog", chx_FileSystemLog.Checked.ToString());

            Registry.SetValue(registry, "IIF_Error", chx_Trace.Checked.ToString());

            Registry.SetValue(registry, "Information_Message", chx_Proceso.Checked.ToString());

            Registry.SetValue(registry, "IO_Error", chx_Error.Checked.ToString());

            Registry.SetValue(registry, "Success_Message", chx_SuccessMessage.Checked.ToString());

            Registry.SetValue(registry, "System_Error", chx_Bitacora.Checked.ToString());

            MessageBox.Show("La configuración  de registro ha sido guardada exitosamente.", "Unisys Duplicate Check Service Configurator", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public void loadRegistryEntries()
        {
            try
            {
                String registry = "HKEY_LOCAL_MACHINE\\Software\\Unisys\\Unisys Duplicate Check Service";
                if (Registry.GetValue(registry, "Configuration_Error", true).Equals("True"))
                { chx_ConfigurationError.Checked = true; }

                if (Registry.GetValue(registry, "FileSystemLog", true).Equals("True"))
                { chx_FileSystemLog.Checked = true; }

                if (Registry.GetValue(registry, "IIF_Error", true).Equals("True"))
                { chx_Trace.Checked = true; }

                if (Registry.GetValue(registry, "Information_Message", true).Equals("True"))
                { chx_Proceso.Checked = true; }

                if (Registry.GetValue(registry, "IO_Error", true).Equals("True"))
                { chx_Error.Checked = true; }

                if (Registry.GetValue(registry, "Success_Message", true).Equals("True"))
                { chx_SuccessMessage.Checked = true; }

                if (Registry.GetValue(registry, "System_Error", true).Equals("True"))
                { chx_Bitacora.Checked = true; }
            }
            catch (Exception w) { /*MessageBox.Show(w.Message);*/ }
        }

        private void chx_FileSystemLog_CheckedChanged(object sender, EventArgs e)
        {
            chx_Bitacora.Checked = chx_FileSystemLog.Checked;
            chx_Trace.Checked = chx_FileSystemLog.Checked;
            chx_Error.Checked = chx_FileSystemLog.Checked;
            chx_Proceso.Checked = chx_FileSystemLog.Checked;
        }

        
    }
}
